import Vue from 'vue'
import App from './App.vue'
import router from './router'
import VeeValidate, { Validator } from 'vee-validate';
import zh_CN from 'vee-validate/dist/locale/zh_CN';
import Vant from 'vant'
import store from './store'
import 'vant/lib/index.css'
import '@/styles/common.less'
import '@/util/rem'
import axios from '@/util/axios';
import getQueryString from '@/util/getQueryString'
import '@/util/dateUtil'
import {
  GET_OPENID,
  STATION_CHECK,
  GET_TOKEN,
  GET_DETAIL
} from '@/api/user'
import { Toast } from 'vant'
import bus from '@/util/Bus'
import VueI18n from 'vue-i18n';
import echarts from 'echarts';
// import { CHECK_TOKEN } from './api/user';
// import { async } from 'q';
// import VConsole from 'vconsole'; //vconsole工具

import 'url-search-params-polyfill';
// var vConsole = new VConsole();
Vue.use(VueI18n)
Vue.use(Toast);
Vue.use(Vant);
Vue.use(axios);
Vue.prototype.$getQueryString = getQueryString;
Vue.prototype.$echarts = echarts;
Vue.config.productionTip = false;

//校验插件中文需要
const i18n = new VueI18n({
  locale: 'zh_CN',
})
//注册校验插件
Vue.use(VeeValidate, {
  i18n,
  i18nRootKey: 'validation',
  dictionary: {
    zh_CN
  }
});

//校验扩展
Validator.extend('required', {
  getMessage:field => field + '不能为空',
  validate: value => {
    if(value && value.replace){
      value = value.replace(/\s/g, '');
    }
    return value !== '' && value !== undefined && value !== null;
  }
});
Validator.extend('mobile', {
    getMessage:field => '请输入正确的手机号码',
    validate: value => {
      return value.length == 11 && /^((1)\d{10})$/.test(value)
    }
});

Validator.extend('price', {
  getMessage:field => '请输入正确的数字',
  validate: value => {
    return /^(0|[1-9][0-9]*)(\.\d+)?$/.test(value)
  }
});
Validator.extend('isInteger', {
  getMessage:field => '请输入正确的数字',
  validate: value => {
    return /^[1-9]\d*|0$/.test(value)
  }
});

Validator.extend('special', {
  getMessage:field => '请不要输入特殊字符',
  validate: value => {
    return !(new RegExp("[`~!@#$^&*()=|{}':;',\\[\\].<>/?~！@#￥……&*（）——|{}【】‘；：”“'。，、？]").test(value))
  }
});

//日期格式化
Date.prototype.Format = function(fmt) {
	var o = {
		"M+": this.getMonth() + 1, //月份 
		"d+": this.getDate(), //日 
		"h+": this.getHours(), //小时 
		"m+": this.getMinutes(), //分 
		"s+": this.getSeconds(), //秒 
		"q+": Math.floor((this.getMonth() + 3) / 3), //季度 
		"S": this.getMilliseconds() //毫秒 
	};
	if(/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
	for(var k in o)
		if(new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
	return fmt;
}


//vconsole
// let vConsole = new VConsole();
sessionStorage.setItem('gdkey', '1476801fe67b9bbb3f21d3a76c49eb3f');

router.beforeEach(async (to, from, next) => {
  if (to.name == 'register' || to.name == 'checking' || to.name == 'edit') {
    next();
    return;
  }
  let openid = sessionStorage.getItem('openid');
  let status = sessionStorage.getItem('status');
  // let showTip = sessionStorage.getItem('showTip');
  if (openid !== null) {
    //获取status
    if (status == null) {
      console.log('获取status')
      let res = await bus.$reqGet(STATION_CHECK, {
        openid: openid
      });
      status = res.data.status;
      sessionStorage.setItem('status', status);
      next('/');

    } else {
      if (status == 2) {
        console.log('去审核页面');
        //审核页面
        router.push({
          name: 'checking'
        });
        return;
      } else if (status == 0) {
        console.log('去注册页面');
        //注册页面
        router.push({
          name: 'register'
        });
        return;
      } else if (status == 3) {
        console.log('去重新审核页面');
        //注册页面
        router.push({
          name: 'edit'
        });
        return;
      }
      //获取token
      if (sessionStorage.getItem('token') == null) {
        console.log('获取token')
        let tokenRes = await bus.$reqGet(GET_TOKEN, {
          openid: openid
        });
        sessionStorage.setItem('token', tokenRes.token);
        //获取配送站信息
        let info = await bus.$reqPost(GET_DETAIL + '?token=' + sessionStorage.getItem('token'));
        console.log(info.data.verify)
        store.dispatch('setStationInfo', info.data);
        
      }

      // if(!showTip){
      //   alert('当前系统属于开发测试阶段，各种操作数据都为测试数据，请勿随意操作，否则水厂不予理会！请等待系统正式上线，开放平台供大家使用！');
      //   sessionStorage.setItem('showTip', true);
      // }
      
      next();
    }
  } else {
    //获取openid
    let openidRes = await bus.$reqGet(GET_OPENID, {code: getQueryString('code')});
    // let openidRes = {openid: 'oHvxRv0VgpnzuYKSaUccvBsnepX4'}       //me
    // let openidRes = {openid: 'oHvxRvzh0O-Ov6PxbZEY9hN_VdoA'}      //朱
    
    //获取openid
    if (openidRes && openidRes.openid) {
      openid = openidRes.openid;
      sessionStorage.setItem('openid', openid);
      next('/')
    }
  }
});

//注册返回指令
Vue.directive('back', {
  bind(el) {
    el.addEventListener("click",function(e){
      router.go(-1);
    },false);
  }
});

new Vue({
  store,
  router,
  render: h => h(App),
  created() {
    if (sessionStorage.getItem("store")) {
      this.$store.replaceState(
        Object.assign({},
          this.$store.state,
          JSON.parse(sessionStorage.getItem("store"))
        )
      );
      sessionStorage.removeItem("store");
    }
    //刷新前保存store
    window.addEventListener("beforeunload", () => {
      sessionStorage.setItem("store", JSON.stringify(this.$store.state));
    });
  }
}).$mount('#app')
